<?php
/**
 * 客户端请求示例 - 完整的PHP代码
 * 这是提供给客户的标准调用示例
 */

class DeviceApiClient
{
    private $baseUrl;
    private $apiKey;
    private $secretKey;
    
    public function __construct($baseUrl, $apiKey, $secretKey)
    {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->apiKey = $apiKey;
        $this->secretKey = $secretKey;
    }
    
    /**
     * 发送设备指令
     * 
     * @param array $requestData 请求数据
     * @return array 响应结果
     */
    public function sendDeviceCommand($requestData)
    {
        $url = $this->baseUrl . '/api/device/command';
        return $this->makeRequest('POST', '/api/device/command', $requestData, $url);
    }
    
    /**
     * 发送API请求
     * 
     * @param string $method HTTP方法
     * @param string $path 请求路径
     * @param array $data 请求数据
     * @param string $fullUrl 完整URL
     * @return array 响应结果
     */
    private function makeRequest($method, $path, $data, $fullUrl)
    {
        // 第1步: 准备请求数据
        $body = json_encode($data, JSON_UNESCAPED_UNICODE);
        $timestamp = time();
        
        echo "=== 第1步: 准备请求数据 ===\n";
        echo "请求方法: {$method}\n";
        echo "请求路径: {$path}\n";
        echo "请求体: {$body}\n";
        echo "时间戳: {$timestamp}\n\n";
        
        // 第2步: 构建待签名字符串
        $stringToSign = strtoupper($method) . "\n" . 
                       $path . "\n" . 
                       $timestamp . "\n" . 
                       $body;
        
        echo "=== 第2步: 构建待签名字符串 ===\n";
        echo "待签名字符串:\n";
        echo "'{$stringToSign}'\n\n";
        
        // 第3步: 计算签名
        $signature = hash_hmac('sha256', $stringToSign, $this->secretKey);
        
        echo "=== 第3步: 计算签名 ===\n";
        echo "签名密钥: {$this->secretKey}\n";
        echo "计算得到的签名: {$signature}\n\n";
        
        // 第4步: 构建请求头
        $headers = [
            'Authorization: ApiKey ' . $this->apiKey,
            'Timestamp: ' . $timestamp,
            'Signature: ' . $signature,
            'Content-Type: application/json',
            'X-Request-ID: ' . uniqid('req_')
        ];
        
        echo "=== 第4步: 构建请求头 ===\n";
        foreach ($headers as $header) {
            echo "{$header}\n";
        }
        echo "\n";
        
        // 第5步: 发送HTTP请求
        echo "=== 第5步: 发送HTTP请求 ===\n";
        echo "请求URL: {$fullUrl}\n";
        echo "注意: 当前已跳过IP白名单验证，可以从任何IP访问\n";
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $fullUrl,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_SSL_VERIFYPEER => false, // 测试环境可以关闭SSL验证
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        echo "HTTP状态码: {$httpCode}\n";
        echo "响应内容: {$response}\n";
        
        if ($error) {
            echo "cURL错误: {$error}\n";
            return ['success' => false, 'error' => $error];
        }
        
        $responseData = json_decode($response, true);
        
        return [
            'success' => $httpCode >= 200 && $httpCode < 300,
            'http_code' => $httpCode,
            'response' => $responseData
        ];
    }
}

// 使用示例
echo "=== 设备API调用示例 ===\n\n";

// 客户从我们这里获得的API凭证
$apiCredentials = [
    'api_key' => 'ak_3d97ebf664db97f3023b336f5fc0ad23',
    'secret_key' => 'e61b4d35cf2a29e46e08e36dd075ea585614cd91470719c4411d2b946f677e12'
];

// 创建API客户端
$client = new DeviceApiClient(
    'http://localhost:8000',  // 我们提供的API服务器地址
    $apiCredentials['api_key'],
    $apiCredentials['secret_key']
);

// 示例1: 单设备重启（简化版）
echo "=== 示例1: 单设备重启 ===\n";
$rebootRequest = [
    'device_id' => '1C3426522542',
    'commands' => [
        'cmds' => [
            [
                'cmd_name' => 'reboot'
            ]
        ]
    ]
];

$result1 = $client->sendDeviceCommand($rebootRequest);
echo "请求结果: " . json_encode($result1, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n\n";

// 示例2: 热点配置（简化版）
echo "=== 示例2: 热点配置 ===\n";
$hotspotRequest = [
    'device_id' => '1C3426522542',
    'commands' => [
        'cmds' => [
            [
                'cmd_name' => 'hotspot_modify',
                'cmd_params' => [
                    'hotspot_name' => 'Customer_WiFi',
                    'hotspot_password' => 'SecurePass123',
                    'hotspot_connected_num_max' => 20,
                    'hotspot_whether_hide' => 0,
                    'hotspot_band' => 1
                ]
            ]
        ]
    ]
];

$result2 = $client->sendDeviceCommand($hotspotRequest);
echo "请求结果: " . json_encode($result2, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n\n";

// 示例3: 多个指令组合
echo "=== 示例3: 多个指令组合 ===\n";
$multiRequest = [
    'device_id' => '1C3426522542',
    'commands' => [
        'cmds' => [
            ['cmd_name' => 'hotspot_on'],
            [
                'cmd_name' => 'network_speed_limit',
                'cmd_params' => [
                    'type' => 'all',
                    'unit' => 'MB',
                    'value' => 10
                ]
            ],
            ['cmd_name' => 'upload_now']
        ]
    ]
];

$result3 = $client->sendDeviceCommand($multiRequest);
echo "请求结果: " . json_encode($result3, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n\n";

// 生成等效的cURL命令
echo "=== 等效的cURL命令 ===\n";
$method = 'POST';
$path = '/api/device/command';
$body = json_encode($rebootRequest, JSON_UNESCAPED_UNICODE);
$timestamp = time();
$stringToSign = strtoupper($method) . "\n" . $path . "\n" . $timestamp . "\n" . $body;
$signature = hash_hmac('sha256', $stringToSign, $apiCredentials['secret_key']);

echo "curl -X POST 'http://localhost:8000/api/device/command' \\\n";
echo "  -H 'Authorization: ApiKey {$apiCredentials['api_key']}' \\\n";
echo "  -H 'Timestamp: {$timestamp}' \\\n";
echo "  -H 'Signature: {$signature}' \\\n";
echo "  -H 'Content-Type: application/json' \\\n";
echo "  -d '{$body}'\n\n";

echo "=== 签名计算过程 ===\n";
echo "1. 待签名字符串: '{$stringToSign}'\n";
echo "2. 签名密钥: {$apiCredentials['secret_key']}\n";
echo "3. 签名算法: HMAC-SHA256\n";
echo "4. 计算结果: {$signature}\n";
?>
